import { useEffect, useState } from "react"

interface UserData {
   name: string;
   email: string;
   username: string;
   phone: string;
   website: string;
   id: number;
}

export default function Effect () {

  // const [count, setCount] = useState(0)
  // const [name, setName] = useState('pipi')
  
  // useEffect(() => {
  //   // 组件渲染会重新执行
  //   // 可以获取元素 发送请求
  //   console.log('useEffect');
  //   let timer = setTimeout(() => {
  //     // 请求接口
  //     console.log('请求接口');
  //   }, 500);
  //   return () => {
  //     clearTimeout(timer)
  //     console.log('组件更新之前/卸载时执行');
  //   }
    
  // },[count,name])   // count依赖项变化会重新执行 空数组只执行一次

  const [userId,setUserId] = useState('1')
  const [userData,setUserData] = useState<UserData | null>(null)
  const [loading,setLoading] = useState<boolean>(true)

  useEffect(() => {
    setLoading(true)
    fetch(`http://localhost:3000/api/${userId}`).then(res => res.json()).then(res => {
      setUserData(res)
      setLoading(false)
    })
  },[userId])
  return (
    <>
      {/* <h1>useEffect</h1>
      <button onClick={() => {
        setCount(count + 1)
      }}>点击</button>
      <input onChange={(e) => setName(e.target.value)} value={name} type="text" /> */}

      <input value={userId} onChange={(e) => setUserId(e.target.value)} type="text" />
      <div>
        {loading ? 'loading...' : <div>
          <div>{userData?.name}</div>
          <div>{userData?.email}</div>
          <div>{userData?.username}</div>
          <div>{userData?.phone}</div>
          <div>{userData?.website}</div>
          <div>{userData?.id}</div>
        </div>}
      </div>
    </>
  )
}
